import { useAPIUtils } from "@/components/APIUtilsProvider";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import UserPill from "@/components/UserPill";
import {
  Box,
  Button,
  Card,
  Divider,
  Flex,
  Grid,
  Group,
  Image,
  Indicator,
  Paper,
  SimpleGrid,
  Space,
  Switch,
  Text,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useState } from "react";
import { useParams } from "react-router-dom";
import BusinessRoleRenderer from "./BusinessRoleRenderer";

export default function BusinessUserDetails() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const userQuery = tanstackQuery(`/api/admin/users/${id}`);

  if (!userQuery.data) {
    return <></>;
  }

  const user = userQuery.data;

  const showPrepaid = user.businessRoles.includes("AG_SHOP");

  return (
    <PageLayout title={"用户详情"}>
      <Grid w="96%">
        <Grid.Col span={7}>
          <Basics user={user} />
          {showPrepaid && <PrepaidWallet />}
          <Divider mt={"xl"} />
          <Recipients user={user} />
        </Grid.Col>
        <Grid.Col span={2} offset={3}>
          <SideContent />
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

const Descriptions = ({ title, data }) => {
  return (
    <Box padding="md">
      {title && (
        <Title order={6} mb={"lg"}>
          {title}
        </Title>
      )}
      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </>
        ))}
      </Grid>
    </Box>
  );
};

function Basics({ user }) {
  const descriptionsData = [
    {
      label: "昵称",
      value: (
        <Group gap="0.25rem">
          <Text>{user.user.nickname}</Text>
          <BusinessRoleRenderer role={user.highestRole} />
        </Group>
      ),
    },
    { label: "电话", value: user.user.mobile },
    { label: "Ta的邀请码", value: user.user.inviteCode },
    { label: "邀请Ta的人", value: <UserPill userId={user.user.invitedBy} /> },
  ];
  return <Descriptions title={`ID: ${user.id}`} data={descriptionsData} />;
}

function PrepaidWallet() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const query = tanstackQuery(`/api/admin/users/${id}/prepaidWallet`);
  const changePrepaidBalance = async (v, action) => {
    const regex = /^\d+(\.\d{1,2})?$/;
    if (!regex.test(v) || parseFloat(v) <= 0) {
      notifications.show({
        title: "请填写正确的数字类型，至多两位小数",
        color: "red",
      });
      return;
    }

    let amount = parseFloat(v);

    await restPUT(
      `/api/admin/prepaidWallet/${id}/balance?amount=${amount}&action=${action}`,
      {}
    );
    tanstackInvalidate(`/api/admin/users/${id}/prepaidWallet`);
  };

  if (!query.data) {
    return <></>;
  }

  const descriptionsData = [
    {
      label: "预付货款余额",
      value: (
        <Group justify="space-between">
          <Text>{query.data.balance}</Text>
          <Group>
            <Button
              color="blue"
              radius="md"
              variant="light"
              size="xs"
              onClick={() =>
                moreModals.openPromptModal({
                  title: "请输入要充值金额",
                  type: "positive-decimal",
                  onConfirm: (v) => {
                    changePrepaidBalance(v, "INCREASE");
                  },
                })
              }
            >
              充值
            </Button>
            <Button
              color="blue"
              radius="md"
              variant="light"
              size="xs"
              onClick={() =>
                moreModals.openPromptModal({
                  title: "请输入要抵扣金额",
                  type: "positive-decimal",
                  onConfirm: (v) => {
                    changePrepaidBalance(v, "DECREASE");
                  },
                })
              }
            >
              抵扣
            </Button>

            <Button
              color=""
              radius="md"
              variant="subtle"
              size="xs"
              onClick={() => window.open(`/prepaid/${id}/operations`, "_blank")}
            >
              查看变动记录
            </Button>
          </Group>
        </Group>
      ),
      block: true,
    },
  ];
  return (
    <>
      <Space h="md" />
      <Descriptions data={descriptionsData} />
    </>
  );
}

function SideContent() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const [checked, setChecked] = useState(false);
  const userQuery = tanstackQuery(`/api/admin/users/${id}`);

  const changePassword = async (newPassword) => {
    await restPUT(`/api/admin/users/${id}/password`, { newPassword });
  };

  const changeMobile = async (newMobile) => {
    await restPUT(`/api/admin/users/${id}/mobile`, { newMobile });
  };

  if (!userQuery.data) {
    return <></>;
  }

  const user = userQuery.data;
  return (
    <>
      <Flex justify={"flex-end"}>
        <Switch
          mb="sm"
          checked={checked}
          label="显示二维码"
          labelPosition="left"
          onChange={(event) => setChecked(event.currentTarget.checked)}
        />
      </Flex>

      <Card shadow="md" padding="lg" radius="md">
        <Card.Section>
          <Image
            src={checked ? user.user.meta.qrCode : user.user.meta.avatar}
            alt=""
          />
        </Card.Section>
        <RenderIf auth="NonPartyAUserManagement">
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入新密码，8位以上的数字和字母组合",
                onConfirm: changePassword,
              })
            }
          >
            修改密码
          </Button>
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入新手机号（格式不验证）",
                onConfirm: changeMobile,
              })
            }
          >
            修改注册手机号
          </Button>
        </RenderIf>
      </Card>
    </>
  );
}

function Recipients({ user }) {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const query = tanstackQuery(`/api/admin/users/${user.id}/recipients`);
  if (!query.data) {
    return <></>;
  }

  return (
    <>
      <Space h="md" />

      <Title order={6} mb={"lg"}>
        {"Ta的收货地址"}
      </Title>

      <SimpleGrid cols={4}>
        {query.data.map((data, index) => (
          <RecipientCard key={index} data={data} />
        ))}
      </SimpleGrid>
    </>
  );
}

function RecipientCard({ data }) {
  return (
    <Indicator
      inline
      label={<Text size="0.5rem">默认</Text>}
      size={16}
      disabled={!data.asDefault}
      color="yellow"
    >
      <Paper shadow="sm" radius="md" p="sm">
        <Group justify="flex-start">
          <Text size="sm">{data.contact}</Text>
        </Group>
        <Text size="xs">{data.phone}</Text>
        <Text size="xs">{data.address}</Text>
      </Paper>
    </Indicator>
  );
}
